here::i_am("R/DependencyFigures.R")
library(here)
library(ggpubr)
library(readr)
library(ggplot2)
library(dplyr)
library(scales)
library(jsonlite)

# Define colors 
component_colors <- c(
  "Final Demand" = "#4472C4",        # Blue for final demand
  "Intermediate Trade" = "#E74C3C"   # Red for intermediate trade
)

# Figure A: Relative values-----

df_shares <- read_csv(here("data", "tidy", "dependency_shares.csv"), show_col_types = FALSE)

# Create totals data for background bars (using Total Trade percentages)
totals_data_pct <- df_shares %>%
  filter(dependency_type == "Total Trade") %>%
  select(category, percentage) %>%
  rename(TotalTradePct = percentage)

# Create component data for foreground bars
# We need both Final Demand and Intermediate Trade percentages
final_demand_pct <- df_shares %>%
  filter(dependency_type == "Final Demand") %>%
  select(category, percentage) %>%
  rename(final_demand_pct = percentage)

total_trade_pct <- df_shares %>%
  filter(dependency_type == "Total Trade") %>%
  select(category, percentage) %>%
  rename(total_trade_pct = percentage)

# Combine and calculate intermediate percentage
components_data_pct <- final_demand_pct %>%
  left_join(total_trade_pct, by = "category") %>%
  mutate(
    intermediate_pct = total_trade_pct - final_demand_pct
  ) %>%
  select(category, final_demand_pct, intermediate_pct) %>%
  tidyr::pivot_longer(
    cols = c(final_demand_pct, intermediate_pct),
    names_to = "component_type",
    values_to = "percentage"
  ) %>%
  mutate(
    component_type = case_when(
      component_type == "final_demand_pct" ~ "Final Demand",
      component_type == "intermediate_pct" ~ "Intermediate Trade"
    ),
    # Ensure proper ordering for dodging
    component_type = factor(component_type, levels = c("Final Demand", "Intermediate Trade"))
  )

# Reorder categories by total trade percentage for consistency with Plot B
category_order_pct <- totals_data_pct %>%
  arrange(desc(TotalTradePct)) %>%
  pull(category)

totals_data_pct$category <- factor(
  totals_data_pct$category, 
  levels = category_order_pct)
components_data_pct$category <- factor(
  components_data_pct$category, 
  levels = category_order_pct)

totals_data_pct <- totals_data_pct |> 
  mutate(category_label=case_when(
    category == "Employee Compensation" ~ "Employee\n Compensation",
    category == "Net Mixed Income" ~ "Net Mixed\n Income",
    category == "Net Operating Surplus" ~ "Net Operating\n Surplus",
    .default = category
  ))
# Create the percentage baseline bar chart

# For Plot A (Percentage chart):
p_percentage <- ggplot() +
  
  # Layer 1: Gray background bars
  geom_col(
    data = totals_data_pct,
    aes(x = category, y = TotalTradePct),
    fill = "grey85",
    alpha = 0.8,
    width = 0.8
  ) +
  
  # Layer 2: Colored component bars
  geom_col(
    data = components_data_pct,
    aes(x = category, y = percentage, fill = component_type),
    position = position_dodge(width = 0.8),
    width = 0.7
  ) +
  
  # Layer 3: Component labels
  geom_text(
    data = components_data_pct,
    aes(x = category, y = percentage, 
        label = paste0(round(percentage, 1), "%"), 
        group = component_type),
    position = position_dodge(width = 0.8),
    vjust = -0.5,
    size = 3,
    family = "sans"
  ) +
  
  # Layer 4: Total labels
  geom_text(
    data = totals_data_pct,
    aes(x = category, y = TotalTradePct, 
        label = paste0("Total: ", round(TotalTradePct, 1), "%")),
    vjust = -2.5,
    size = 3.5,
    fontface = "bold",
    family = "sans"
  ) +
  
  # Layer 5: Category labels - BACK above individual bars but with more space
  geom_text(
    data = totals_data_pct,
    aes(x = category, y = TotalTradePct, label = category_label),
    vjust = -2.5,  # Further above the bars
    size = 4,
    fontface = "bold",
    family = "sans"
  ) +
  
  scale_fill_manual(values = component_colors) +
  
  ggtitle("Relative Trade Dependencies: \nFinal Demand vs Intermediate Trade") +
  
  theme_void(base_size = 12, base_family = "sans") +
  theme(
    plot.title = element_text(
      hjust = 0.5,
      face = "bold",
      size = 16,
      margin = margin(b = 15)  # Consistent title spacing
    ),
    
    legend.position = "top",
    legend.justification = "center",
    legend.title = element_blank(),
    legend.text = element_text(size = 11),
    legend.key.size = unit(0.5, "cm"),
    legend.margin = margin(b = -10),
    
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_blank(),
    
    plot.margin = margin(20, 20, 20, 20)
  ) +
  
  # INCREASED y-axis limits to prevent cutoff
  scale_y_continuous(
    limits = c(0, max(totals_data_pct$TotalTradePct) * 1.35),  # More space for labels
    expand = expansion(mult = c(0, 0))
  )

# Figure B: Absolute values-----
# Prepare data for the baseline bar chart
# We need both the background totals and the individual components
df_stacked <- read_csv(here("data", "tidy", "dependency_stacked.csv"), show_col_types = FALSE)

baseline_data <- df_stacked %>%
  select(category, final_demand_millions, total_trade_millions) %>%
  mutate(
    # Calculate intermediate component
    intermediate_trade_millions = total_trade_millions - final_demand_millions
  )

# Create totals data for background bars
totals_data <- baseline_data %>%
  select(category, total_trade_millions) %>%
  rename(TotalTrade = total_trade_millions) |> 
  mutate(category_label=case_when(
    category == "Employee Compensation" ~ "Employee\n Compensation",
    category == "Net Mixed Income" ~ "Net Mixed\n Income",
    category == "Net Operating Surplus" ~ "Net Operating\n Surplus",
    .default = category
  ))

# Create component data for foreground bars (reshape to long format)
components_data <- baseline_data %>%
  select(category, final_demand_millions, intermediate_trade_millions) %>%
  tidyr::pivot_longer(
    cols = c(final_demand_millions, intermediate_trade_millions),
    names_to = "component_type",
    values_to = "amount"
  ) %>%
  mutate(
    component_type = case_when(
      component_type == "final_demand_millions" ~ "Final Demand",
      component_type == "intermediate_trade_millions" ~ "Intermediate Trade"
    ),
    # Ensure proper ordering for dodging
    component_type = factor(component_type, levels = c("Final Demand", "Intermediate Trade"))
  )

# Reorder categories by total trade for better visual hierarchy
category_order <- totals_data %>%
  arrange(desc(TotalTrade)) %>%
  pull(category)

# Alternatively, use same order as in figure A:
category_order <- category_order_pct

totals_data$category <- factor(totals_data$category, levels = category_order)
components_data$category <- factor(components_data$category, levels = category_order)

# Create the baseline bar chart
p_absolute <- ggplot() +
  
  # Layer 1: Gray background bars
  geom_col(
    data = totals_data,
    aes(x = category, y = TotalTrade),
    fill = "grey85",
    alpha = 0.8,
    width = 0.8
  ) +
  
  # Layer 2: Colored component bars
  geom_col(
    data = components_data,
    aes(x = category, y = amount, fill = component_type),
    position = position_dodge(width = 0.8),
    width = 0.7
  ) +
  
  # Layer 3: Component labels
  geom_text(
    data = components_data,
    aes(x = category, y = amount, 
        label = paste0("$", round(amount, 0), "M"), 
        group = component_type),
    position = position_dodge(width = 0.8),
    vjust = -0.5,
    size = 3,
    family = "sans"
  ) +
  
  # Layer 4: Total labels
  geom_text(
    data = totals_data,
    aes(x = category, y = TotalTrade, 
        label = paste0("Total: $", round(TotalTrade, 0), "M")),
    vjust = -2.5,
    size = 3.5,
    fontface = "bold",
    family = "sans"
  ) +
  
  # Layer 5: Category labels - BACK above individual bars but with more space
  geom_text(
    data = totals_data,
    aes(x = category, y = TotalTrade, label = category_label),
    vjust = -2.5,  # Further above the bars
    size = 4,
    fontface = "bold",
    family = "sans"
  ) +
  
  scale_fill_manual(values = component_colors) +
  
  ggtitle("Absolute Trade Dependencies: \nFinal Demand vs Intermediate Trade") +
  
  theme_void(base_size = 12, base_family = "sans") +
  theme(
    plot.title = element_text(
      hjust = 0.5,
      face = "bold",
      size = 16,
      margin = margin(b = 15)  # SAME title spacing as Plot A
    ),
    
    legend.position = "top",
    legend.justification = "center",
    legend.title = element_blank(),
    legend.text = element_text(size = 11),
    legend.key.size = unit(0.5, "cm"),
    legend.margin = margin(b = -10),
    
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    axis.title = element_blank(),
    
    plot.margin = margin(20, 20, 20, 20)
  ) +
  
  # INCREASED y-axis limits to prevent cutoff
  scale_y_continuous(
    limits = c(0, max(totals_data$TotalTrade) * 1.35),  # More space for labels
    expand = expansion(mult = c(0, 0))
  )

# Create the combined figure
full_fig <- ggpubr::ggarrange(
  p_percentage, p_absolute, 
  ncol = 2, common.legend = TRUE, labels = c("A)", "B)"),
  legend = "bottom"
)


full_fig_v2 <- ggpubr::ggarrange(
  p_percentage, p_absolute, 
  ncol = 2, 
  common.legend = TRUE, 
  labels = c("A)", "B)"),
  legend = "bottom",
  legend.grob = get_legend(p_percentage)  # Extract legend manually
)

# Save the figure

full_fig_manual <- ggpubr::ggarrange(
  p_percentage, p_absolute, 
  ncol = 2, 
  common.legend = TRUE, 
  labels = c("A)", "B)"),
  legend = "bottom",
  font.label = list(size = 14, face = "bold")
) 

# Add some padding around the entire plot
full_fig_padded <- ggpubr::annotate_figure(
  full_fig_manual,
  bottom = text_grob("", size = 10)  # Add some bottom space
)

ggsave(here("output", "DependencySharesAggregate.png"),
       full_fig_padded,
       width = 10, height = 6.8, dpi = 300, bg = "white")
